package com.sondon.dev_soceket.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * @Project : Java_C_Socket_Maven
 * @Package : com.sondon.netty
 * @Class : DeviceTCPServer.java
 * @Company 广州讯动网络科技有限公司
 * @Author : 蔡文锋
 * @DateTime：2015年4月22日 下午5:52:18
 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
 * @Description : {Neety启动类}
 */
public final class DeviceTCPServer {

	static final boolean SSL = System.getProperty("ssl") != null;
	static final int PORT = Integer
			.parseInt(System.getProperty("port", "8322"));

	public static void main(String[] args) throws Exception {
		// Configure SSL.
		final SslContext sslCtx;
		if (SSL) {
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			sslCtx = SslContext.newServerContext(ssc.certificate(),
					ssc.privateKey());
		} else {
			sslCtx = null;
		}

		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			/*
			 * Netty5中ByteBuf对象的创建方式对内存的影响
			 * http://xiaochu.blog.51cto.com/1048262/1588426
			 */
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new DeviceTCPServerInitializer(sslCtx))
					.option(ChannelOption.SO_BACKLOG, 1024)
					.option(ChannelOption.SO_RCVBUF, 1024 * 256)
					.option(ChannelOption.SO_SNDBUF, 1024 * 256)
					.option(ChannelOption.ALLOCATOR,
							PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.ALLOCATOR,
							PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.SO_KEEPALIVE, true);

			b.bind(PORT).sync().channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
